package tw.com.com;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

import org.apache.log4j.Logger;

import tw.com.web.GetPage;

public class MyReader {

	final Logger logger = Logger.getLogger(GetPage.class);
	private String path;
	private String content;
	private Map<String, String> settings = new HashMap<String, String>();
	// PRIVATE
	private File fFile;

	public void ReadWithScanner(String aFileName) {
		logger.debug("MyReader processLineByLine File=" + aFileName);

		fFile = new File(aFileName);
	}

	public final void processLineByLine(String fileName) throws FileNotFoundException {
		
		logger.debug("MyReader processLineByLine");
		
		this.ReadWithScanner(fileName);
		
		// Note that FileReader is used, not File, since File is not Closeable
		Scanner scanner = new Scanner(new FileReader(fFile));
		try {
			// first use a Scanner to get each line
			while (scanner.hasNextLine()) {
				processLine(scanner.nextLine());
			}
		} catch (Exception e) {
			logger.debug(e.getMessage());

		}

		finally {
			// ensure the underlying stream is always closed
			// this only has any effect if the item passed to the Scanner
			// constructor implements Closeable (which it does in this case).

			scanner.close();
		}
	}

	protected void processLine(String aLine) {
		// use a second Scanner to parse the content of each line
		Scanner scanner = new Scanner(aLine);
		scanner.useDelimiter("=");
		if (scanner.hasNext()) {
			String name = scanner.next();
			String value = scanner.next();

			settings.put(name, value);
	
			logger.debug("Name is : " + quote(name.trim()) + ", and Value is : "
					+ quote(value.trim()));
		} else {
			log("Empty or invalid line. Unable to process.");
		}
		// no need to call scanner.close(), since the source is a String
	}

	private String quote(String aText) {
		String QUOTE = "'";
		return QUOTE + aText + QUOTE;
	}

	private static void log(Object aObject) {
		System.out.println(String.valueOf(aObject));
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public File getfFile() {
		return fFile;
	}

	@Override
	public String toString() {
		return "MyReader [path=" + path + ", content=" + content
				+ ", settings=" + settings + ", fFile=" + fFile + "]";
	}

	public Map<String, String> getSettings() {
		return settings;
	}

	public void setSettings(Map<String, String> settings) {
		this.settings = settings;
	}

	public void setfFile(File fFile) {
		this.fFile = fFile;
	}

}
